package crm.salesOrderProcessing.session;

import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import crm.salesOrderProcessing.entity.DeliveryOrderEntity;

@Stateless
@LocalBean
public class DeliveryOrderSessionBean {

    @PersistenceContext
    private EntityManager em;

    public void addDeliveryOrder(DeliveryOrderEntity deliveryOrder) {
        em.persist(deliveryOrder);
    }

    public DeliveryOrderEntity getDeliveryOrderById(Long deliveryOrderId) {
        return em.find(DeliveryOrderEntity.class, deliveryOrderId);
    }
    public List<DeliveryOrderEntity> getAll(){
       Query query = em.createQuery("SELECT u FROM DeliveryOrderEntity u");
       return query.getResultList();
   }
    public List<DeliveryOrderEntity> getAllDeliveryOrders() {
        Query query = em.createQuery("SELECT u FROM DeliveryOrderEntity u WHERE u.isCIAPayment =0 AND u.paymentStatus =0 Order by u.id");
        return query.getResultList();
    }

    public List<DeliveryOrderEntity> getAllCIADeliveryOrders() {
        Query query = em.createQuery("SELECT u FROM DeliveryOrderEntity u WHERE u.isCIAPayment =1 AND u.paymentStatus =0 Order by u.id");
   return query.getResultList();
    }

    public Boolean checkId(Long Id) {
        boolean available = false;

        if (em.find(DeliveryOrderEntity.class, Id) == null) {
            available = true;
        }
        return available;
    }

    public void saveChanges(DeliveryOrderEntity deliveryOrder) {
        em.merge(deliveryOrder);
        em.flush();
    }

    public void remove(Long selectedDeliveryOrderId) {
        DeliveryOrderEntity selectedDeliveryOrder = em.find(DeliveryOrderEntity.class, selectedDeliveryOrderId);
        em.remove(selectedDeliveryOrder);
    }

    public void removeDeliveryOrderById(Long deliveryOrderId) {
        System.out.println("Remove Test...." + deliveryOrderId);
        DeliveryOrderEntity deliveryOrder = em.find(DeliveryOrderEntity.class, deliveryOrderId);
        deliveryOrder.setBillingAddress(null);
        deliveryOrder.setDeliveryOrderLineItems(null);
        deliveryOrder.setParentSalesOrder(null);
        em.remove(deliveryOrder);
    }
}
